<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="params.paymentType"  :clearable="true" placeholder="请选择支付方式">
        <el-option
          v-for="(item,value) in paymentTypes"
          :key="value"
          :label="item.title"
          :value="item.value">
        </el-option>
        </el-select>
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="params.startTime"
          type="date"
          placeholder="选择开始日期"
        ></el-date-picker>
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="params.endTime"
          type="date"
          placeholder="选择结束日期"
        ></el-date-picker>
        <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px;"
        clearable
        class="filter-item"
        placeholder="会员号"
        v-model="params['virtualcard']"
      ></el-input>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-document"
          @click="exportExcelFile"
        >导出</el-button>
    </div>
    <el-table
      :height="tableHeight"
      :data="dataList"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="virtualcard" align="center" label="会员号" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.virtualcard}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="receiver" align="center" label="收货人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.receiver}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="telephone" align="center" label="手机号码" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.telephone}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" align="center" label="商品名称" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.goodsName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goodsNo" align="center" label="商品编码" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.goodsNo}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="saleCount" align="center" label="销售数量" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.saleCount}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="salePrice" align="center" label="售价" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.salePrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="workdate" align="center" label="营业日期" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.workdate}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="paymentType" align="center" label="支付方式" width="120">
        <template slot-scope="scope">
          <span>{{paymentTypeFilter(scope.row.paymentType)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="收货地址" width="220">
        <template slot-scope="scope">
          <span>{{scope.row.address}}</span>
        </template>
      </el-table-column>

      <el-table-column width="180" prop="createTime" align="center" label="申请时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime|parseTime}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column width="140" prop="auditStatus" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.auditStatus | statusTagFilter"
          >{{scope.row.auditStatus|statusFilter}}</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="操作" width="230" class-name="small-padding">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            v-if="~accessable.indexOf('order-supplement:passed') && (scope.row.auditStatus==1)"
            @click="agreeSupplement(scope.row)"
          >审核通过</el-button>
          <el-button
            type="danger"
            size="mini"
            v-if="~accessable.indexOf('order-supplement:reject') && (scope.row.auditStatus==1)"
            @click="rejectSupplement(scope.row)"
          >审核拒绝</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules"
        ref="dataForm"
        class="dialog-form"
        :model="temp"
        label-position="left"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员号" prop="virtualcard">
              <el-input v-model="temp.virtualcard" placeholder="会员号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiver">
              <el-input v-model="temp.receiver" placeholder="收货人"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="telephone">
              <el-input v-model="temp.telephone" placeholder="手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业日期" prop="workdate">
              <el-date-picker
                :editable="false"
                v-model="temp.workdate"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="营业日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收货人地址" prop="address">
          <el-input v-model="temp.address" placeholder="收货人地址"></el-input>
        </el-form-item>
        <el-form-item label="补录数据" prop="orderSupplementDetails">
          <div class="clearfix">
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="6">
                  商品编码
                </el-col>
                <el-col :span="6">
                  商品名称
                </el-col>
                <el-col :span="6">
                  销售价格
                </el-col>
                <el-col :span="6">
                  销售数量
                </el-col>
              </el-row>
            </div>
          </div>
          <div
            class="clearfix"
            v-for="(detail,idx) in temp.orderSupplementDetails"
            v-if="!detail.deleted"
            :key="idx"
          >
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-input v-model="detail.goodsNo" prop="goodsNo" placeholder="商品编码"/>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="detail.goodsName" placeholder="商品名称"/>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="detail.salePrice" placeholder="销售价格"/>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="detail.saleCount" placeholder="销售数量"/>
                </el-col>
              </el-row>
            </div>
            <div class="fr">
              <el-button
                type="danger"
                @click="deleteOrderSupplementDetail(detail,idx)"
                size="mini"
              >删除</el-button>
            </div>
          </div>
          <div class="clearfix">
            <el-button type="primary" @click="addOrderSupplementDetail" size="mini">添加补录商品</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.lcontent {
  margin-right: 90px;
  width: 88%;
  float: left;
}
.clearfix {
  position: relative;
  margin-bottom: 10px;
}
.clearfix::after {
  content: " ";
  display: table;
  height: 0;
  width: 0;
  clear: both;
}
.fr {
  position: absolute;
  right: 0;
  top: 0;
}
.workflow{
    padding-top:20px;
}
.workflow table{
    border-collapse: collapse;
    margin-top: 10px;
}
.workflow th,.workflow td{
    padding: 10px;
    border:1px solid #eee;

}
</style>

<script>
let statusMap = ['审核中', '补录完成', '审核不通过', '已作废']
export default {
  data () {
    const validateOrderSupplementDetails = (rule, value, callback) => {
      if (value && value.length) {
        value.every(el => {
          // goodsNo,goodsName,salePrice,saleCount
          if (!el.goodsNo || !el.goodsNo.trim()) {
            callback(new Error('商品编码不能为空'))
            return false
          }
          if (!el.goodsName || !el.goodsName.trim()) {
            callback(new Error('商品名称不能为空'))
            return false
          }
          if (!el.salePrice || !el.salePrice.toString().trim()) {
            callback(new Error('销售价格不能为空'))
            return false
          }
          if (isNaN(el.salePrice)) {
            callback(new Error('销售价格必须为正确的数字'))
            return false
          }
          if (!el.saleCount || !el.saleCount.toString().trim()) {
            callback(new Error('销售数量不能为空'))
            return false
          }
          if (!/^\d+$/.test(el.saleCount)) {
            callback(new Error('销售数量必须为整数'))
            return false
          }
          return true
        })
        callback()
      } else {
        callback()
      }
    }
    return {
      tableHeight: 0,
      statusMap: statusMap,
      total: 0,
      paymentTypes: [],
      dataList: [],
      listLoading: false,
      temp: {
        id: '',
        workdate: '',
        virtualcard: '',
        orderSupplementDetails: [],
        receiver: '',
        address: '',
        telephone: ''
      },
      rules: {
        virtualcard: [
          {
            required: true,
            message: '会员号不能为空',
            trigger: 'change'
          }
        ],
        receiver: [
          {
            required: true,
            message: '收货人不能为空',
            trigger: 'change'
          }
        ],
        telephone: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'change'
          }
        ],
        workdate: [
          {
            required: true,
            message: '营业日期不能为空',
            trigger: 'change'
          }
        ],
        address: [
          {
            required: true,
            message: '收货人地址不能为空',
            trigger: 'change'
          }
        ],
        orderSupplementDetails: [
          {
            required: true,
            message: '补录数据不能为空',
            trigger: 'array'
          },
          {
            validator: validateOrderSupplementDetails,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.tableHeight = window.innerHeight - 300
    this.loadPaymentTypes()
    this.loadData()
  },
  filters: {
    auditStatusFilter (status) {
      const statusMap = ['提交', '审核通过', '审核不通过', '重新提交']
      return statusMap[parseInt(status)]
    },
    statusFilter (status) {
      return statusMap[parseInt(status) - 1]
    },
    statusTagFilter (status) {
      status = parseInt(status)
      return ['warning', 'primary', 'success', 'danger', 'info'][status]
    }
  },
  methods: {
    paymentTypeFilter (payment) {
      if (!payment) {
        return ''
      }
      let c
      return (c = this.paymentTypes.filter(el => el.value === payment)) && c[0].title
    },
    agreeSupplement (row) {
      if (this.isAgreeSupplement) {
        return
      }
      this.$$comfirm('确认审核通过该补录吗?', (res) => {
        this.isAgreeSupplement = true
        this.$post('/admin/order-supplement/audit-supplement', {id: row.id, passed: true}).then(_ => {
          this.$$notify('操作成功')
          this.loadData()
        }).finally(_ => {
          this.isAgreeSupplement = false
        })
      })
    },
    loadPaymentTypes () {
      this.$post('/admin/order-supplement/payments').then(data => {
        this.paymentTypes = data
      })
    },
    rejectSupplement (row) {
      if (this.isRejectSupplement) {
        return
      }
      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[^\s]+/,
        inputErrorMessage: '请输入拒绝理由'
      }).then(({ value }) => {
        this.isRejectSupplement = true
        this.$post('/admin/order-supplement/audit-supplement', {id: row.id, passed: false, auditAdvize: value.trim()}).then(_ => {
          this.$$notify('操作成功')
          this.loadData()
        }).finally(_ => {
          this.isRejectSupplement = false
        })
      }).catch(() => {

      })
    },
    cancelSupplement (row) {
      this.$post('/admin/order-supplement/cancel-supplement', {id: row.id}).then(data => {
        this.$$notify('作废成功')
        row.auditStatus = 4
      })
    },
    submitSupplement (row) {
      this.$post('/admin/order-supplement/submit-order-supplement', {id: row.id}).then(data => {
        this.$$notify('提交成功')
        this.loadData()
      })
    },
    handleFilter () {
      this.loadData()
    },
    handleCurrentChange (page) {
      this.params.page = page
      this.loadData()
    },
    handleSizeChange (size) {
      this.params.pageSize = size
      this.loadData()
    },
    submitForm () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          const postData = Object.assign({}, this.temp)
          postData.orderSupplementDetails.forEach((el, idx) => {
            Object.keys(el).forEach(k => {
              postData['orderSupplementDetails[' + idx + '].' + k] = el[k]
            })
          })
          if (!postData.id) {
            delete postData.id
          }
          delete postData.orderSupplementDetails
          let url = '/admin/order-supplement/create-supplement'
          if (this.isEditing) {
            url = '/admin/order-supplement/modify-supplement'
          }
          this.$post(url, postData)
            .then(data => {
              this.loadData()
              this.$$notify('操作成功')
              this.dialogFormVisible = false
            })
            .finally(_ => {
              this.submiting = false
            })
        }
      })
    },
    addOrderSupplementDetail () {
      this.temp.orderSupplementDetails.push({})
    },
    deleteOrderSupplementDetail (detail, idx) {
      const id = detail.id
      if (!id) {
        this.temp.orderSupplementDetails.splice(idx, 1)
      } else {
        detail.deleted = true
      }
    },
    loadData () {
      this.listLoading = true
      this.$post(
        '/admin/order-supplement/supplemented',
        this.params
      )
        .then(data => {
          this.total = data.total
          this.dataList = data.orderSupplements
        })
        .finally(_ => {
          this.listLoading = false
        })
    },
    __onAfterHandleEditUpdate (row) {},
    __onFormSubmit (row) {
      this.temp._roleIds = this.temp.roleIds.join(',')
    },
    exportExcel (method, options) {
      this._parseFilters()
      this._parseParams()
      return this.$model.addParam(options).query('/admin/' + method)
    },
    exportExcelFile () {
      this.$post('/admin/order-supplement/supplemented/export', {
        paymentType: this.params.paymentType,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        virtualcard: this.params.virtualcard,
        title: '补录记录',
        fields: JSON.stringify([
          {
            field: 'virtualcard',
            title: '会员号'
          },
          {
            field: 'receiver',
            title: '收货人'
          },
          {
            field: 'telephone',
            title: '手机号码'
          },
          {
            field: 'goodsName',
            title: '商品名称'
          },
          {
            field: 'goodsNo',
            title: '商品编码'
          },
          {
            field: 'saleCount',
            title: '销售数量'
          },
          {
            field: 'salePrice',
            title: '售价'
          },
          {
            field: 'workdate',
            title: '营业日期'
          },
          {
            field: 'paymentType',
            title: '支付方式',
            valueMap: this.paymentTypes.reduce(function (prev, el) { prev[el.value] = el.title; return prev }, {})
          },
          {
            field: 'address',
            title: '收货地址'
          },
          {
            field: 'createTime',
            title: '申请时间'
          }
        ])
      }).then(res => {
        this.openWin(res)
      })
    }
  }
}
</script>
